//
//  ApiHelper.m
//  uneed
//
//  Created by apple on 3/23/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "ApiHelper.h"
//#import "Log.h"

static NSString * const BOUNDRY        = @"--------------------------7d71a819230404";


@interface ApiHelper(Private) 


@end


@implementation  ApiHelper(Private) 


- (void)connection:(NSURLConnection *)connection   
  didFailWithError:(NSError *)error            {
//    CMLog(@"NSURLCOnnection ERROR!");
	NSArray *ret_arr = [NSArray arrayWithObjects:[NSNumber numberWithInt:mIndex],error,nil];
//	NSString *_ret_str = [NSString stringWithFormat:@"%@",[ret_arr JSONString]];
	[mdelegate performSelector: errorSelector  withObject:ret_arr];
}

- (void)connection:(NSURLConnection *)connection     
	didReceiveData:(NSData *)data              {
// 	CMLog(@"NSURLConnection ReceivedData!");
	[self.reply appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Set appIcon and clear temporary data/image
    NSString *ret_str = [[NSString alloc] initWithData:self.reply encoding:NSUTF8StringEncoding];
	NSArray *ret_arr = [NSArray arrayWithObjects:[NSNumber numberWithInt:mIndex],ret_str,nil];
    
    // call our delegate and tell it that our icon is ready for display
//	NSString *_ret_str = [NSString stringWithFormat:@"%@",[ret_arr JSONString]];

	[mdelegate performSelector:doneSelector  withObject:ret_arr];
//    [mdelegate appImageDidLoad:self.indexPathInTableView];
}


@end


@implementation ApiHelper

@synthesize reply;

-(id)  initWithUrl:(NSString*) urlPath 
		  postData:(NSDictionary*)  data
		  delegate:(id)  aDeletgate
		 withIndex:(int)theIndex
   onErrorCallback:(SEL) errorCallback
onCompletedCallback:(SEL) complectedCallback
{
	if (self=[super init]) {
		requestUrlPath =[[NSString stringWithString:  urlPath] lowercaseString] ;
        reply = [[NSMutableData alloc]init];
		mdelegate=[  aDeletgate retain];
		mIndex = theIndex;
		errorSelector= errorCallback;
		doneSelector = complectedCallback ;
		NSURL  * url=[NSURL URLWithString:requestUrlPath] ;
		NSMutableURLRequest  * req=[NSMutableURLRequest requestWithURL: url];
		if (data != nil ) {
			
			[req setHTTPMethod:@"POST"];
			[req setValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BOUNDRY]
		forHTTPHeaderField:@"Content-Type"];
			int len=512;
			NSMutableData  * postData =[NSMutableData dataWithCapacity:len];
		//	NSMutableData  * postData =[NSMutableData data];
			[postData  appendData: [[NSString  stringWithFormat:@"--%@\r\n",BOUNDRY] 
									dataUsingEncoding:NSUTF8StringEncoding]];
			int  i=0;
			int  cnt=data.count ;
			
			for ( NSString * key in  [data allKeys]) 
			{
				[postData  appendData: [[NSString  stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key ] 
										dataUsingEncoding:NSUTF8StringEncoding]];
				[postData  appendData: [[NSString  stringWithFormat:@"%@",[data objectForKey:key ]] 
										dataUsingEncoding:NSUTF8StringEncoding]];
				if( i != cnt -1  ){
					[postData  appendData: [[NSString  stringWithFormat:@"\r\n--%@\r\n",BOUNDRY] 
											dataUsingEncoding:NSUTF8StringEncoding]];
				}
				i++ ;
			}
			[postData  appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",BOUNDRY]
								   dataUsingEncoding:NSUTF8StringEncoding]];
			[req  setHTTPBody:postData];
		}
		else {
			[req  setHTTPMethod:@"GET"];
		}
		
		NSURLConnection * connection =[[[NSURLConnection alloc] initWithRequest:req delegate:self] autorelease];
		if(!connection  ){ 
			NSDictionary * errorInfo=[NSDictionary dictionaryWithObjectsAndKeys:@"发送请求失败" ,@"errorKey", nil];
			NSError * error=[NSError  errorWithDomain:@"www.mainaer.com" code:100 userInfo:  errorInfo];
			NSArray *ret_arr = [NSArray arrayWithObjects:[NSNumber numberWithInt:mIndex],error,nil];
//			NSString *_ret_str = [NSString stringWithFormat:@"%@",[ret_arr JSONString]];
			[mdelegate performSelector:errorCallback withObject:ret_arr];
		}  else {
//			CMLog(@"Send Data Request \n");
		}
		
	}
	return self ;
}


- (void)dealloc
{
    [reply release];
    [mdelegate release];
	mdelegate = nil;
	
    doneSelector = NULL;
    errorSelector = NULL;
    [super dealloc];
}


@end
